import { message } from 'antd';
import { history } from 'umi';

// jscs:disable
export default {
  /**
   *
   * @param key 存储数据的key
   * @param json 存储数据的值
   * @param expires 有效时间(毫秒)
   */
  setStorage: function (key: string, json: object, expires?: number) {
    const obj = {
      value: json,
      expires: expires,
      startTime: new Date().getTime(),
    };
    try {
      if (obj.expires) {
        // 如果设置了时间，把obj转换数据类型转换为字符串对象存起来
        localStorage.setItem(key, JSON.stringify(obj));
      } else {
        // 如果没有设置有效时间，直接把value值存进去
        localStorage.setItem(key, JSON.stringify(json));
      }
    } catch (err: any) {
      console.log(err.message);
    }
  },

  getStorage: function (key: string) {
    const json = localStorage.getItem(key);
    if (typeof json == 'string' && json !== undefined && json !== 'undefined') {
      try {
        const data = JSON.parse(json);
        // 是否设置了有效期
        if (data.expires) {
          const date = new Date().getTime();
          // 判断是否过期
          if (date - data.startTime > data.expires) {
            this.removeStorage(key);
            return;
          } else {
            return data.value;
          }
        }
        // 未设置,则直接输出
        else {
          return data;
        }
      } catch (err) {
        console.log(err);
        return false;
      }
    }
  },

  removeStorage: function (key: string) {
    localStorage.removeItem(key);
  },

  removeAllStorage: function () {
    localStorage.clear();
  },

  isUrl: function (str: string) {
    const v = new RegExp(
      '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
      'i',
    );
    return v.test(str);
  },
  addTab: function (dispatch: any, payload: any) {
    dispatch({
      type: 'common/addTab',
      payload,
    });
    history.push({
      pathname: payload.path,
      state: payload.state,
    });
  },
  setNewTab: function (dispatch: any, tab: any) {
    dispatch({
      type: 'common/setNewTab',
      payload: {
        curTab: tab,
      },
    });
  },
  // 下载图片
  handleDownImage: (imgSrc: any) => {
    const canvas: any = document.createElement('canvas');
    const img = document.createElement('img');
    img.onload = (e) => {
      canvas.width = img.width;
      canvas.height = img.height;
      const context = canvas.getContext('2d');
      context?.drawImage(img, 0, 0, img.width, img.height);
      canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
      canvas.toBlob((blob: any) => {
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '';
        link.click();
      }, 'image/jpeg');
    };
    img.setAttribute('crossOrigin', '*');
    img.src = imgSrc;
  },
  /**
   * 获取26因为字母数组
   */
  getAllChars: () => {
    const startChar = 65;
    const arr = [...new Array(26)];
    const allChars = arr.map((item: any, index: number) => String.fromCharCode(startChar + index));
    return allChars;
  },
  /**
   * 复制到剪切板
   */
  copyCot: (cot: string) => {
    const pEle = document.createElement('p');
    pEle.innerHTML = cot || '';
    document.body.appendChild(pEle);

    const range = document.createRange(); // 创造range
    window?.getSelection()?.removeAllRanges(); //清除页面中已有的selection
    range.selectNode(pEle); // 选中需要复制的节点
    window?.getSelection()?.addRange(range); // 执行选中元素

    const copyStatus = document.execCommand('Copy'); // 执行copy操作
    message.info(copyStatus ? '复制成功' : '复制失败'); // 不需要提示 可注释
    document.body.removeChild(pEle);
    window?.getSelection()?.removeAllRanges(); //清除页面中已有的selection
  },
  /**
   *
   * @param data
   * @param key
   * @param target
   * @returns
   */
  getRowSpanCount: (data: any, key: any, target: number) => {
    if (!Array.isArray(data)) return 1;
    data = data.map((_) => _[key]); // 只取出筛选项
    let preValue = data[0];
    const res = [[preValue]]; // 放进二维数组里
    let index = 0; // 二维数组下标
    for (let i = 1; i < data.length; i++) {
      if (data[i] === preValue) {
        // 相同放进二维数组
        res[index].push(data[i]);
      } else {
        // 不相同二维数组下标后移
        index += 1;
        res[index] = [];
        res[index].push(data[i]);
        preValue = data[i];
      }
    }
    const arr: any = [];
    res.forEach((_) => {
      const len = _.length;
      for (let i = 0; i < len; i++) {
        arr.push(i === 0 ? len : 0);
      }
    });
    return arr[target];
  },

  // 下载文件
  onExport: (record: any) => {
    const elelink = document.createElement('a');
    elelink.style.display = 'none';
    elelink.target = '_blank';
    elelink.href = record.url;
    elelink.download = record.name;
    document.body.appendChild(elelink);
    elelink.click();
    document.body.removeChild(elelink);
    message.success('下载完成！');
  },
};
